//
//  AgentDetailViewController.m
//  House
//
//  Created by 张垚 on 16/7/20.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "AgentDetailViewController.h"
#import "AgentDetailMianInfoCollectionViewCell.h"
#import "BaseTitleNavigationBar.h"
#import "AgentDetailIntroductionCollectionViewCell.h"
#import "AgentDetailHouseInfoCollectionViewCell.h"
#import "SegCollectionViewCell.h"
#import "AgentHouseChooseCollectionViewCell.h"
#import "SecondaryDetailViewController.h"
#import "RentHouseDetailViewController.h"
#import "AgentListModel.h"
#import "AgentDetailModel.h"
#import "RentHouseDetailViewController.h"

typedef NS_ENUM(NSUInteger, RequestType) {
    Rent = 0,
    Buy = 1,
};

@interface AgentDetailViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
@property (nonatomic, strong) UIButton *bottomButton;
@property (nonatomic, strong) NSMutableArray *dataDicArr;
@property (nonatomic, copy) NSString *typeStr;

@property (nonatomic, strong) MBProgressHUD *hud;

@end

static NSInteger flag;

@implementation AgentDetailViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    flag = 1;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _dataDicArr = [NSMutableArray array];
    //顶部视图
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:[_model.truename description]];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back:)];
    [_myBar.leftView addGestureRecognizer:tap];
    [self initCollectionView];
    [self initBottomView];
    
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = @"正在加载数据";
    _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.backgroundView.backgroundColor = [UIColor whiteColor];
    _hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    _hud.animationType = MBProgressHUDAnimationZoomIn;
    [self getDataWithCategory:flag];
}
//返回上一界面
- (void)back:(UITapGestureRecognizer *)tap {
    [self.navigationController popViewControllerAnimated:YES];
}
//请求数据
- (void)getDataWithCategory:(NSInteger)category {
    NSString *url;
    NSDictionary *parameters = nil;
    if (_type == 0) {
        url = @"http://aizufang.hrbzjwl.com/tp/api.php/Jingjiren/ziyuan";
        parameters = @{@"page": @"1", @"userid": _model.userid, @"fen": @(category)};
        [NetRequest getWithURLString:url parameters:parameters progress:^(NSProgress *progress) {
        } success:^(id response) {
            if ([[response[@"flag"] description] isEqualToString:@"1"]) {
                _hud.label.text = @"加载成功";
                [_hud hideAnimated:YES afterDelay:1];
                _dataDicArr = [response[@"ziyuan"] mutableCopy];
                
            }else {
                _hud.label.text = @"暂无房源信息";
                [_hud hideAnimated:YES afterDelay:1];
                _dataDicArr = [NSMutableArray array];
            }
            [_collectionView reloadData];
            
        } failure:^(NSError *error) {
            _hud.label.text = @"服务器异常";
            [_hud hideAnimated:YES afterDelay:1];
            
        }];
    } else {
        url = @"http://aizufang.hrbzjwl.com/tp/api.php/Jiamengshang/xiangqing";
        parameters = @{@"userid": _model.userid, @"key": @(category)};
        [NetRequest getWithURLString:url parameters:parameters progress:^(NSProgress *progress) {
        } success:^(id response) {
            if ([[response[@"flag"] description] isEqualToString:@"1"]) {
                if ([response[@"ziyuan"][@"zu"] isKindOfClass:[NSNull class]]) {
                    _hud.label.text = @"暂无房源信息";
                    [_hud hideAnimated:YES afterDelay:1];
                    _dataDicArr = [NSMutableArray array];
                }else {
                    _hud.label.text = @"加载成功";
                    [_hud hideAnimated:YES afterDelay:1];
                    _dataDicArr = response[@"ziyuan"][@"zu"];
                }
                [_collectionView reloadData];
            }else {
                _hud.label.text = @"暂无房源信息";
                [_hud hideAnimated:YES afterDelay:1];
            }
            
        } failure:^(NSError *error) {
            _hud.label.text = @"服务器异常";
            [_hud hideAnimated:YES afterDelay:1];
            
        }];
    }
}

//- (void)setFooterRefresh {
//    [_collectionView.mj_footer beginRefreshing];
//    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        //每刷一次 请求的页数叠加
//        page++;
//        NSDictionary *dic = @{@"page": [NSString stringWithFormat:@"%ld", (long)page], @"userid": _model.userid, @"fen": [NSString stringWithFormat:@"%d", flag]};
//        //网络请求数据
//        [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/Jingjiren/ziyuan" parameters:dic progress:^(NSProgress *progress) {
//        } success:^(id response) {
//            //没有数据 显示已加载全部数据
//            if (response[@"ziyuan"] == NULL ) {
//                [_collectionView.mj_footer endRefreshingWithNoMoreData];
//            }
//            //否则数据一直叠加并且刷新tableview显示
//            else {
//                for (NSDictionary *dic in response[@"ziyuan"]) {
//                    [_dataDicArr addObject:dic];
//                }
//                [_collectionView reloadData];
//                [_collectionView.mj_footer endRefreshing];
//            }
//        } failure:^(NSError *error) {
//            NSLog(@"%@", error);
//        }];
//    }];
//
//}

#pragma mark - 底部视图
- (void)initBottomView {
    UIView *superView = self.view;
    _bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_bottomButton];
    _bottomButton.backgroundColor = [UIColor orangeColor];
    [_bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.bottom.equalTo(superView.mas_bottom);
        make.height.equalTo(@50);
    }];
    [_bottomButton setTitle:@"咨询电话" forState:UIControlStateNormal];
    _bottomButton.titleLabel.font = [UIFont systemFontOfSize:20 weight:15];
    [_bottomButton addTarget:self action:@selector(callPhone:) forControlEvents:UIControlEventTouchUpInside];
}
//拨打经纪人电话
- (void)callPhone:(UIButton *)button {
    NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",_model.mobile];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
#pragma mark - collectionView
- (void)initCollectionView {
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 114) collectionViewLayout:flow];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[AgentDetailMianInfoCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([AgentDetailMianInfoCollectionViewCell class])];
    [_collectionView registerClass:[AgentDetailIntroductionCollectionViewCell  class] forCellWithReuseIdentifier:NSStringFromClass([AgentDetailIntroductionCollectionViewCell class])];
    [_collectionView registerClass:[AgentDetailHouseInfoCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([AgentDetailHouseInfoCollectionViewCell class])];
    [_collectionView registerClass:[SegCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([SegCollectionViewCell class])];
    [_collectionView registerClass:[AgentHouseChooseCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([AgentHouseChooseCollectionViewCell class])];
    _collectionView.showsVerticalScrollIndicator = NO;
}
//分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 6;
}
//每个分区中item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 5) {
        return _dataDicArr.count;
    }else {
       return 1;
    }
    
}
//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        AgentDetailMianInfoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AgentDetailMianInfoCollectionViewCell class]) forIndexPath:indexPath];
        cell.model = _model;
        return cell;
    }else if (indexPath.section == 2){
        AgentDetailIntroductionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AgentDetailIntroductionCollectionViewCell class]) forIndexPath:indexPath];
        cell.model = _model;
        return cell;
    }else if (indexPath.section == 4) {
        AgentHouseChooseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AgentHouseChooseCollectionViewCell class]) forIndexPath:indexPath];
        [cell.secondaryButton addTarget:self action:@selector(getSecondaryData:) forControlEvents:UIControlEventTouchUpInside];
        [cell.rentHouseButton addTarget:self action:@selector(getRentHouseData:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    else if (indexPath.section == 5){
        AgentDetailHouseInfoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AgentDetailHouseInfoCollectionViewCell class]) forIndexPath:indexPath];
        NSDictionary *dic = _dataDicArr[indexPath.item];
        AgentDetailModel *model = [AgentDetailModel modelWithDic:dic];
        cell.flag = flag;
        cell.model = model;
        return cell;
    }else {
        SegCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SegCollectionViewCell class]) forIndexPath:indexPath];
        return cell;
    }
   
}

- (void)getSecondaryData:(UIButton *)button {
    flag = button.tag;
    [self getDataWithCategory:button.tag];
}
- (void)getRentHouseData:(UIButton *)button {
    flag = button.tag;
    [self getDataWithCategory:button.tag];
}

//item高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth, 200);
    }else if (indexPath.section == 2) {
        CGSize size = [_model.personal boundingRectWithSize:CGSizeMake(kScreenWidth - 30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
         return (CGSize){kScreenWidth,size.height + 80};
    }else if (indexPath.section == 4) {
       return (CGSize){kScreenWidth,60};
    }
    else if (indexPath.section == 5){
         return (CGSize){kScreenWidth / 2 - 5,180};
    }else {
        return CGSizeMake(kScreenWidth, 10);
    }
}
//cell点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 5) {
        NSDictionary *dic = _dataDicArr[indexPath.item];
        AgentDetailModel *model = [AgentDetailModel modelWithDic:dic];
        if (flag == 1) {
            RentHouseDetailViewController *rentHouseVC = [[RentHouseDetailViewController alloc] init];
            rentHouseVC.itemid = model.itemid;
            [self.navigationController pushViewController:rentHouseVC animated:YES];
        }else {
            SecondaryDetailViewController *secondaryVC = [[SecondaryDetailViewController alloc] init];
            secondaryVC.itemID = model.itemid;
            [self.navigationController pushViewController:secondaryVC animated:YES];
        }
        
    }
    
}

@end
